import 'package:get/get.dart';
import '../model/single_chat_model.dart';
import '../data/single_chat_data.dart';
import '../data/single_chat_message_data.dart';

/// 单聊列表状态管理（含未读数）
/// 使用GetX进行全局状态管理
class SingleChatState extends GetxController {
  // 所有单聊
  final RxList<SingleChatModel> _allChats = <SingleChatModel>[].obs;

  // 当前用户ID（默认admin: '1'）
  final RxString _currentUserId = '1'.obs;

  /// 获取所有单聊
  List<SingleChatModel> get allChats => _allChats.toList();

  /// 获取当前用户ID
  String get currentUserId => _currentUserId.value;

  /// 设置当前用户ID
  void setCurrentUserId(String userId) {
    _currentUserId.value = userId;
    update();
  }

  /// 获取当前用户参与的聊天
  List<SingleChatModel> get myChats {
    return _allChats
        .where((chat) => chat.isUserInChat(_currentUserId.value))
        .toList()
      ..sort((a, b) {
        final aTime = a.lastMessageTime ?? a.createTime;
        final bTime = b.lastMessageTime ?? b.createTime;
        return bTime.compareTo(aTime);
      });
  }

  /// 计算指定聊天的未读消息数（相对当前用户）
  int getChatUnreadCount(String chatId) {
    return SingleChatMessageData.getChatUnreadCount(
      chatId,
      _currentUserId.value,
    );
  }

  /// 获取全部未读消息数
  int get totalUnreadCount {
    return SingleChatMessageData.getUnreadCount(_currentUserId.value);
  }

  /// 根据另一个用户ID查找聊天
  SingleChatModel? getChatWithUser(String otherUserId) {
    try {
      return _allChats.firstWhere(
        (c) =>
            c.userIds.contains(otherUserId) &&
            c.userIds.contains(_currentUserId.value),
      );
    } catch (_) {
      return null;
    }
  }

  /// 新建一个聊天（若不存在则创建）
  SingleChatModel ensureChatWithUser(String otherUserId) {
    final existed = getChatWithUser(otherUserId);
    if (existed != null) return existed;

    final newChat = SingleChatModel(
      id: 'single_chat_${DateTime.now().millisecondsSinceEpoch}',
      userIds: <String>[_currentUserId.value, otherUserId],
      createTime: DateTime.now(),
      lastMessage: null,
      lastMessageSenderId: null,
      lastMessageTime: null,
    );
    _allChats.insert(0, newChat);
    update();
    return newChat;
  }

  /// 更新聊天的最后一条消息元信息
  void updateChatLastMessage({
    required String chatId,
    required String content,
    required String senderId,
    required DateTime sendTime,
  }) {
    final index = _allChats.indexWhere((c) => c.id == chatId);
    if (index == -1) return;
    final updated = _allChats[index].copyWith(
      lastMessage: content,
      lastMessageSenderId: senderId,
      lastMessageTime: sendTime,
    );
    _allChats[index] = updated;
    _allChats.refresh();
    update();
  }

  /// 删除聊天
  void removeChat(String chatId) {
    _allChats.removeWhere((c) => c.id == chatId);
    update();
  }

  /// 清空某个聊天的最近消息信息
  void clearChatLastMessage(String chatId) {
    final index = _allChats.indexWhere((c) => c.id == chatId);
    if (index == -1) return;
    final updated = _allChats[index].copyWith(
      lastMessage: null,
      lastMessageSenderId: null,
      lastMessageTime: null,
    );
    _allChats[index] = updated;
    _allChats.refresh();
    update();
  }

  /// 清空
  void clearAllChats() {
    _allChats.clear();
    update();
  }

  @override
  void onInit() {
    super.onInit();
    _loadDefaultData();
  }

  void _loadDefaultData() {
    _allChats.assignAll(SingleChatData.getDefaultSingleChats());
  }
}
